package mycommunity.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.hql.ast.HqlASTFactory;

import mycommunity.dao.TopicDao;
import mycommunity.entity.Topic;
import mycommunity.util.HibernateUtil;

public class TopicDaoImpl implements TopicDao{

	@Override
	public List<Topic> getTopics(int fid, String keyWord, int startRow, int length, boolean isBest) {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.openSession();
		String hql="from Topic where 1=1";
		Map<String, Object> param = new HashMap<>();
		if (fid!=0) {
			hql += " and forum.id=:fid";
			param.put("fid", fid);
		}
		if (keyWord!=null && !keyWord.isEmpty()) {
			hql += " and title like :keyWord";
			param.put("keyWord", "%"+keyWord+"%");
		}
		hql += " and isBest = :isBest order by updateTime desc";
		param.put("isBest", isBest);
		try {
			if (isBest) {
				return session.createQuery(hql)
						.setProperties(param)
						.list();
			}else {
				return session.createQuery(hql)
						.setProperties(param)
						.setFirstResult(length*(startRow-1))
						.setMaxResults(length)
						.list();
			}
		} finally {
			// TODO: handle finally clause
			session.close();
		}
	}

	@Override
	public int getRow(int fid, String keyWord) {
		Session session = HibernateUtil.openSession();
		String hql="select count(id) from Topic where 1=1";
		Map<String, Object> param = new HashMap<>();
		if (fid!=0) {
			hql += " and forum.id=:fid";
			param.put("fid", fid);
		}
		if (keyWord!=null && !keyWord.isEmpty()) {
			hql += " and title like :keyWord";
			param.put("keyWord", "%"+keyWord+"%");
		}
		hql += " and isBest = false";
		try {
			Number number = (Number) session.createQuery(hql).setProperties(param).uniqueResult();
			return number.intValue();
		} finally {
			// TODO: handle finally clause
			session.close();
		}
	}
	public static void main(String[] args) {
		TopicDao topicDao = new TopicDaoImpl();
		System.out.println(topicDao.getTopics(3, null, 1, 3,false).get(0).getAuthor().getNickname());
	}

	@Override
	public List<Topic> geAllTopic(int fid, String keyWord, int startRow, int length) {
		Session session = HibernateUtil.openSession();
		String hql="from Topic where 1=1";
		Map<String, Object> param = new HashMap<>();
		if (fid!=0) {
			hql += " and forum.id=:fid";
			param.put("fid", fid);
		}
		if (keyWord!=null && !keyWord.isEmpty()) {
			hql += " and title like :keyWord";
			param.put("keyWord", "%"+keyWord+"%");
		}
		hql += "order by updateTime desc";
		try {
			
			return session.createQuery(hql)
					.setProperties(param)
					.setFirstResult(length*(startRow-1))
					.setMaxResults(length)
					.list();
		} finally {
			// TODO: handle finally clause
			session.close();
		}
	}
	
}
